package com.lori.order.service.imp;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import redis.clients.jedis.JedisCluster;

import com.lori.netshop.mapper.TbOrderItemMapper;
import com.lori.netshop.mapper.TbOrderMapper;
import com.lori.netshop.mapper.TbOrderShippingMapper;
import com.lori.netshop.pojo.TbOrder;
import com.lori.netshop.pojo.TbOrderItem;
import com.lori.netshop.pojo.TbOrderShipping;
import com.lori.netshop.util.NetshopResult;
import com.lori.order.mapper.OrderMapper;
import com.lori.order.pojo.Order;
import com.lori.order.service.OrderService;
/**
 * 订单创建，修改，删除，更新
 * @author Administrator
 *
 */
@Service
public class OrderServiceimp implements OrderService {
	/**
	 * 订单创建
	 */
	@Autowired
	private JedisCluster rediscolony;
	@Autowired
	private TbOrderMapper tbOrderMapper;
	@Autowired
	private TbOrderItemMapper tbOrderItemMapper;
	@Autowired
	private TbOrderShippingMapper tbOrderShippingMapper;
	
	@Autowired
	private OrderMapper orderMapper;
	
	@Value("${ORDER_GENID_KEY}")
	private String ORDER_GENID_KEY;
	@Value("${ORDER_GENID_ORI}")
	private long ORDER_GENID_ORI;
	@Value("${ITEM_GENID_KEY}")
	private String ITEM_GENID_KEY;
	@Override
	public NetshopResult create(Order order) {
		//保存订单信息
		//通过redis获得自增长id
		long orderId = 0; 
		if(rediscolony.exists("ORDER_GENID_KEY")){
			orderId = rediscolony.incr("ORDER_GENID_KEY");
		}else{
			orderId = rediscolony.incrBy("ORDER_GENID_KEY", ORDER_GENID_ORI);
		}
		System.out.println(orderId);
		//补全信息
		order.setOrderId(orderId+"");
		order.setCreateTime(new Date());
		order.setStatus(1);//'状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭'
		order.setUpdateTime(new Date());
		tbOrderMapper.insert(order);
		//保存订单商品信息
		//遍历
		for(TbOrderItem tbOrderItem:order.getOrderItems()){
			//补全信息
			//获得id
			long orderItemId = rediscolony.incr("ITEM_GENID_KEY");
			tbOrderItem.setId(orderItemId+"");
			tbOrderItem.setOrderId(orderId+"");
			tbOrderItemMapper.insert(tbOrderItem);
		}
		//保存订单物流信息
		//获得物流信息对象
		TbOrderShipping orderShipping = order.getOrderShipping();
		//补全信息
		orderShipping.setOrderId(orderId+"");
		orderShipping.setCreated(new Date());
		orderShipping.setUpdated(new Date());
		tbOrderShippingMapper.insert(orderShipping);
		return NetshopResult.ok(orderId);
	}
	@Override
	public NetshopResult getOrder(long userId) {
		List<TbOrder> orderList = orderMapper.getOrderList(userId);
		return NetshopResult.ok(orderList);
	}

}
